import { Component, ViewChild } from '@angular/core';

import { NavController, ModalController, AlertController, Platform } from 'ionic-angular';

import { Storage } from '@ionic/storage';

import { Common } from "../../../providers/common";
import { Config } from "../../../providers/config";
import {CirculateService} from "./circulate.service";

import _ from "lodash";
import {IpmCirculateModal} from "./circulate.modal";
import { Content } from 'ionic-angular';

@Component({
	selector: 'page-ipm-circulate',
	templateUrl: 'circulate.html',
  providers: [CirculateService]
})
export class IpmCirculatePage{
	moa_page_name: any = "page-ipm-circulate";
  moa_page_explain: any = "打新基金市值管理";

  @ViewChild(Content) content: Content;

  // 列表数据
  listData: any = [];

  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

	hisDays = 20;
	baseValue = 1000;

	showQueryParams = false;
	showQueryCondition = true;

  maxDate = "";

  queryCondition = null;

  selectedFund = [];
  fundCode = "";

  userInfo = null;

	constructor(
		public navCtrl: NavController,
    public common: Common,
    private circulateService: CirculateService,
    public modalCtrl: ModalController,
    public alertCtrl: AlertController,
    public config: Config,
    public  plt: Platform,
    public storage: Storage
	) {
    // this.maxDate = "2099-12-12";//this.common.getNowFormatDate();

    this.initQueryCondition();

  }

  ionViewDidEnter() {
    // document.getElementById("headerDivider").style.transition = null;
  };

  initQueryCondition() {
	  this.queryCondition = {
      fund_code: "",
      l_fut_date_p: "",
      l_days_p: 20,
      en_value0_p: 1000
    };

    this.queryCondition.l_fut_date_p = this.common.getNowFormatDate();

    this.circulateService.getL_fut_date_p(this.queryCondition.l_fut_date_p).subscribe(data => {
      if (data && data[0]) {
        data[0] = data[0].substr(0, 4) + "-" + data[0].substr(4,2) + "-" + data[0].substr(6,2);
        console.log(data[0]);
        this.queryCondition.l_fut_date_p = data[0];
      }
    });
    this.storage.get("userInfo").then(user => {
      this.userInfo = user;
      this.storage.get("selected_fund_circulate" + this.userInfo.loginid).then(selected_fund => {
        if (selected_fund) {
          this.selectedFund = selected_fund;
          this.queryCondition.fund_code = _.toString(_.map(this.selectedFund, "vc_fund_code"));
        }
      });
    });
  }

  selectFund() {
    let profileModal = this.modalCtrl.create(IpmCirculateModal, {
      selectedFund: this.selectedFund
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        this.selectedFund = data;
        this.storage.set("selected_fund_circulate"  + this.userInfo.loginid, data);
        this.queryCondition.fund_code = _.toString(_.map(this.selectedFund, "vc_fund_code"));
      }
    });
    profileModal.present();
  }

	setShowQueryCondition() {
	  this.showQueryCondition = !this.showQueryCondition;
	  this.content.scrollToTop();
  }

  setShowQueryParams() {
	  this.showQueryParams = !this.showQueryParams;
  }

  search() {
    this.isLoadMore = true;
	  if (this.queryCondition.fund_code === "") {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: "请选择基金",
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
      return;
    }
	  this.loadListData();
  }

  setShowListItem(fund) {
	  fund.expanded = !fund.expanded;
  }

  /**
   * [loadListData 加载列表数据]
   */
  loadListData() {
    this.circulateService.getListDatas(this.queryCondition).subscribe(data => {
      if (data) {
        this.setShowQueryCondition();
        _.forEach(data, list => {
          list.expanded = false;
          switch (list.l_market_no) {
            case "1001":
              list.l_market_no = "上海";
              break;
            case "1002":
              list.l_market_no = "深圳";
              break;
          }

          let diff = parseInt(this.queryCondition.en_value0_p) * 10000 -  parseFloat(list.en_avg_value_virtual);

          // list.en_value_delta_virtual = 491516318911.15151984;
          list.en_value_delta_virtual = _.toString(parseFloat(list.en_value_delta_virtual) / 10000);
          let float_en_value_delta_virtual = parseFloat(list.en_value_delta_virtual);
          if (float_en_value_delta_virtual < 0) {
            float_en_value_delta_virtual = -float_en_value_delta_virtual;
            if (float_en_value_delta_virtual - parseInt(list.en_value_delta_virtual) != 0) {
              list.en_value_delta_virtual = parseInt(list.en_value_delta_virtual) - 1;
            } else {
              list.en_value_delta_virtual = parseInt(list.en_value_delta_virtual);
            }
          } else {
            if (float_en_value_delta_virtual - parseInt(list.en_value_delta_virtual) != 0) {
              list.en_value_delta_virtual = parseInt(list.en_value_delta_virtual) + 1;
            } else {
              list.en_value_delta_virtual = parseInt(list.en_value_delta_virtual);
            }
          }

          list.en_value_delta = _.toString(parseFloat(list.en_value_delta) / 10000);
          let float_en_value_delta = parseFloat(list.en_value_delta);
          if (float_en_value_delta < 0) {
            float_en_value_delta = -float_en_value_delta;
            if (float_en_value_delta - parseInt(list.en_value_delta) != 0) {
              list.en_value_delta = parseInt(list.en_value_delta) - 1;
            } else {
              list.en_value_delta = parseInt(list.en_value_delta);
            }
          } else {
            if (float_en_value_delta - parseInt(list.en_value_delta) != 0) {
              list.en_value_delta = parseInt(list.en_value_delta) + 1;
            } else {
              list.en_value_delta = parseInt(list.en_value_delta);
            }
          }

          list.en_cur_value = this.common.formatNumberToAccountancy(_.toString(parseInt(_.toString(parseFloat(list.en_cur_value) / 10000))));
          list.en_total_value = this.common.formatNumberToAccountancy(_.toString(parseInt(_.toString(parseFloat(list.en_total_value) / 10000))));
          list.en_avg_value = this.common.formatNumberToAccountancy(_.toString(parseInt(_.toString(parseFloat(list.en_avg_value) /10000))));
          list.en_total_value_virtual = this.common.formatNumberToAccountancy(_.toString(parseInt(_.toString(parseFloat(list.en_total_value_virtual) / 10000))));
          list.en_value_delta = this.common.formatNumberToAccountancy(_.toString(list.en_value_delta));
          list.en_avg_value_virtual = this.common.formatNumberToAccountancy(_.toString(parseInt(_.toString(parseFloat(list.en_avg_value_virtual) / 10000))));

          list.en_value_delta_virtual = this.common.formatNumberToAccountancy(_.toString(list.en_value_delta_virtual));

          /*list.en_cur_value = parseInt(list.en_cur_value);
          list.en_total_value = parseInt(list.en_total_value);
          list.en_avg_value = parseInt(list.en_avg_value);
          list.en_total_value_virtual= parseInt(list.en_total_value_virtual);
          list.en_value_delta = parseInt(list.en_value_delta);
          list.en_avg_value_virtual = parseInt(list.en_avg_value_virtual);
          list.en_value_delta_virtual = parseInt(list.en_value_delta_virtual);*/

          if (diff > 0) {
            list.textColor = "redText";
            list.redHint = "日均：" + list.en_avg_value_virtual + " 万元  "
              + "差额：" + list.en_value_delta_virtual + " 万元";
          } else {
            list.textColor = "";
            list.redHint = "日均：" + list.en_avg_value_virtual + " 万元  "
              + "差额：" + list.en_value_delta_virtual + " 万元";
          }

        });
        this.listData = data;
      } else {
        this.listData = [];
        this.isLoadMore = false;
      }

    });
  }

  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      console.info("-----------infiniteScroll------------");
      console.info(infiniteScroll);
      if (this.isLoadMore) {
        // this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    // this.loadListData(this.pageIndex, null, refresher);
  }

  goPos() {
    let offsetHeight = document.getElementById("inputEnValue").offsetHeight;
    if (this.plt.is("android")) {
      console.log(offsetHeight);
      this.content.scrollTo(0, offsetHeight * 5);
    }
  }

}

